package com.beiding.t;

import com.alibaba.fastjson.JSONObject;
import com.beiding.jsonanalyzer.Analyzer;
import com.beiding.jsonanalyzer.Key;
import org.springframework.util.StreamUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author 丁常磊
 * @date 2021/9/4 10:04
 */

public class 抽取款机日期为json {


    private static final String ROOT_DIR = "C:\\Users\\lenovo\\Documents\\WeChat Files\\wxid_u7l7a4vt6tih22\\FileStorage\\MsgAttach\\8fb48f792d4818834fe88928d937dca4\\File\\2022-06\\日志处理";

    private static final String START_TIME = "2022-06-18 10:00:00";
    private static final String END_TIME = "2023-04-12 16:41:00";

    public static void main(String[] args) {


        //读取日志文件

        File rootDir = new File(ROOT_DIR);

        File[] listFiles = rootDir.listFiles();

        if (listFiles == null) {
            return;
        }

        for (File file : listFiles) {
            if (file.getName().endsWith(".txt")) {
                String fileName = file.getName().substring(0, file.getName().length() - 4);
                String s = readFile(file);
                String[] split = s.split("\n");

                for (int i = 0; i < split.length; i++) {
                    String line = split[i];
                    if (line.contains("url=====>")) {

                        line = line.trim();
                        //调用时间
                        String time = line.substring(0, "xxxx/xx/xx xx:xx:xx.xx".length());

                        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

                        try {
                            Date date = dateFormat.parse(time.substring(0, "xxxx/xx/xx xx:xx:xx".length()));

                            dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                            if (START_TIME != null) {
                                Date sd = dateFormat.parse(START_TIME);
                                if (date.getTime() < sd.getTime()) {
                                    continue;
                                }
                            }

                            if (END_TIME != null) {
                                Date ed = dateFormat.parse(END_TIME);
                                if (date.getTime() > ed.getTime()) {
                                    continue;
                                }
                            }


                        } catch (Exception e) {
                            continue;
                        }

                        //判断一下时间

                        String url = line.substring(line.indexOf("url=====>") + "url=====>".length());

                        String preLine = split[i - 1];

                        //标题
                        String title = preLine.substring(preLine.indexOf("YPopLogic\t") + "YPopLogic\t".length());

                        System.out.println(preLine);
                        System.out.println(line);
                        i++;
                        //请求体行
                        String requestLine = split[i];

                        //请求体
                        String request = requestLine.substring(requestLine.indexOf("request(no zip)=====>") + "request(no zip)=====>".length());
                        System.out.println(requestLine);
                        //响应体行

                        String responseLine = null;

                        for (int j = i + 1; j < split.length; j++) {
                            String t = split[j];
                            if (t.contains("response=====>")) {
                                responseLine = t;
                                i = j;
                                break;
                            }
                        }

                        if (responseLine == null) {
                            throw new RuntimeException("");
                        }

                        //响应体
                        String response = responseLine.substring(responseLine.indexOf("response=====>") + "response=====>".length());
                        System.out.println(responseLine);

                        System.out.println(time + "   " + title);

                     /*   Analyzer read = Analyzer.read("{}");
                        read.set("url地址", url);
                        try {
                            read.set("请求体", JSONObject.read(request));
                        } catch (Exception e) {
                            read.set("请求体", request);
                        }
                        try {
                            read.set("响应结果", JSONObject.read(response));
                        } catch (Exception e) {
                            read.set("响应结果", response);
                        }

                        read.findKeys(Value.eq("6040189190907364")).forEach(key -> {
                            read.set(key, "tttaapp");
                        });*/


                        try {
                            Analyzer read = Analyzer.parse(request);

//                            read.replaceValue("6040189191356146", "112233");

                            System.out.println(read.format());

                            System.out.println("====");

                            File of = new File(rootDir + "\\" + fileName);

                            if (!of.exists()) {
                                of.mkdirs();
                            }

                            url = url.replace("10.161.19.2:80", "10.161.19.53");


                            Analyzer analyzer =new Analyzer(new JSONObject());

                            analyzer.set(Key.parse("url"), url);
                            analyzer.set(Key.parse("request"), read.getJsonObject(Key.parse("")));

                            analyzer.set(Key.parse("response"), JSONObject.parseObject(response));

                            writeFile(of, (time + "   " + title).replace("start...", "").replace("/", "-").replace(":", "_").replace(".", "").replace("\r", "").replace("\t", ""),
                                    analyzer.format()

                            );
                        } catch (Exception e) {
                            System.out.println("解析失败");
                            e.printStackTrace();
                        }


                    }
                }
            }
        }


    }

    private static void writeFile(File jsonOut, String file, String content) {
        File f = new File(jsonOut, file + ".json");
        try {
            FileWriter fileWriter = new FileWriter(f);
            fileWriter.write(content);
            fileWriter.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static String readFile(File f) {
        try {
            FileInputStream fileInputStream = new FileInputStream(f);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            StreamUtils.copy(fileInputStream, byteArrayOutputStream);
            fileInputStream.close();
            return new String(byteArrayOutputStream.toByteArray());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

}
